package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${ruoyi.profile}")
    private String profile;  // 现在将从 "ruoyi.profile" 中读取值

    @PostMapping("/avatar")
    @ResponseBody
    @Anonymous
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传失败，文件为空");
        }

        // 获取文件扩展名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));

        // 生成唯一文件名
        String newFileName = UUID.randomUUID().toString() + fileExtension;

        // 文件保存路径
        File dest = new File(profile + newFileName);

        try {
            // 保存文件
            file.transferTo(dest);

            // 返回上传成功的结果
            return AjaxResult.success("上传成功", newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，服务器错误");
        }
    }
}
